﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using Bzure.Common.Core;
using System.IO;

namespace System
{
    public static class AreaExtensions
    {
        /// <summary>
        /// 获取当前区域名
        /// </summary>
        /// <param name="Public"></param>
        /// <returns></returns>
        public static string GetAreaName(this Public Public)
        {
            HttpContextWrapper hcw = new HttpContextWrapper(HttpContext.Current);
            return Bzure.Mvc.Controllers.AreaHelpers.GetAreaName(RouteTable.Routes.GetRouteData(hcw));
        }
        /// <summary>
        /// 根据Url获取区域名
        /// </summary>
        /// <param name="Public"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetAreaName(this Public Public, string Url)
        {
            return Bzure.Mvc.Controllers.AreaHelpers.GetAreaName(Actor.Public.MatchRouteData(Url));
        }
        public static UrlHelper Url(this Public Public)
        {
            HttpContextWrapper hcw = new HttpContextWrapper(HttpContext.Current);
            return new UrlHelper(new RequestContext(hcw, RouteTable.Routes.GetRouteData(hcw)));
        }
        public static bool CanRoute(this Public Public)
        {
            HttpContextWrapper hcw = new HttpContextWrapper(HttpContext.Current);
            return RouteTable.Routes.GetRouteData(hcw).IsNotNull();
        }
        public static RouteData MatchRouteData(this Public Public, string Url)
        {
            var fullUrl = Url;
            var questionMarkIndex = fullUrl.IndexOf('?');
            string queryString = null;
            var url = Url;
            if (questionMarkIndex != -1) // There is a QueryString
            {
                url = fullUrl.Substring(0, questionMarkIndex);
                queryString = fullUrl.Substring(questionMarkIndex + 1,
                                                fullUrl.Length - questionMarkIndex + 1);
            }
            var request = new HttpRequest(null, url, queryString);
            var response = new HttpResponse(new StringWriter());
            var httpContext = new HttpContext(request, response);
            return RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
        }
    }
}
